package com.zbkj.crmeb.handler.orderproduct;

import com.alibaba.fastjson.JSON;
import com.zbkj.crmeb.plat.by.dto.ImageUploadResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Collections;

@Component
public class FileUploadUtils {



    private static String platUrl;
    @Value("${by.plat.url}")
    public void setPlatUrl(String url) {
        platUrl = url;
    }

    private static String platKey;
    @Value("${by.plat.key}")
    public void setPlatKey(String Key) {
        platKey = Key;
    }

    public static void main(String[] args) throws Exception {
        System.out.println(uploadImageOfBY("https://italytao.oss-cn-shanghai.aliyuncs.com/product-image/buyer/20210224142811_35990.jpg"));

        String urlString = "https://viettistorage.blob.core.windows.net/hub/vietti shop/2022/04/11/20220411233059683_S22---zanellato---6692BDZ9938.JPG";
        urlString = urlString.replace(" ", "%20"); //替换空格为%20
        URL url = new URL(urlString);
        try {
            InputStream is = url.openStream();
            System.out.println();
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        System.out.println();
    }
    public static ImageUploadResponse uploadImageOfBY(String imageUrl){
        InputStream is = null;
        try {
            imageUrl= imageUrl.replaceAll(" ","%20");
            URL url = new URL(imageUrl);
            is = url.openStream();
            if (null == is){
                return null;
            }
            RestTemplate restTemplate = new RestTemplate();
            // 将InputStream转换为字节数组
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) > -1 ) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
            byteArrayOutputStream.flush();
            byte[] bytes = byteArrayOutputStream.toByteArray();
            // 使用字节数组创建一个ByteArrayResource
            String finalImageUrl = imageUrl;
            ByteArrayResource byteArrayResource = new ByteArrayResource(bytes) {
                @Override
                public String getFilename() {
                    String[] parts = finalImageUrl.split("/");
                    return parts[parts.length - 1];
                }
            };
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            MultiValueMap<String,String> header = new LinkedMultiValueMap<>();
            header.put("Authorization",Collections.singletonList(platKey));
            headers.addAll(header);
            // 创建包含文件资源的MultiValueMap
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("file", byteArrayResource);
            // 创建请求实体
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
            String uploadUrl = platUrl+"/inventory/api/v1/files/product/images";
            // 发送POST请求
            String response = restTemplate.postForObject(uploadUrl, requestEntity, String.class);
            if (StringUtils.isBlank(response)){
                return null;
            }
            ImageUploadResponse imageUploadResponse = JSON.parseObject(response, ImageUploadResponse.class);
            imageUploadResponse.setImageName(byteArrayResource.getFilename());
            is.close();
            return imageUploadResponse;
        }catch (Exception e){
            if (null != is){
                try {
                    is.close();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
            return null;
        }


    }
}